package org.yufan.cart.service.impl;

import com.github.abel533.entity.Example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.yufan.bean.Cart;
import org.yufan.bean.Item;
import org.yufan.cart.service.CartService;
import org.yufan.mapper.CartMapper;
import org.yufan.mapper.ItemMapper;

import java.util.Date;
import java.util.List;

/**
 * Created by zxd on 2018/1/3.
 */
@Service("cartService")
@Transactional
public class CartServiceImpl implements CartService{

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private CartMapper cartMapper;

    /**
     * 加入商品到购物车
     * @param itemId
     */
    @Override
    public void addItemToCart(Long itemId,Long userId) {
        Item item=this.itemMapper.selectByPrimaryKey(itemId);
        if(item==null){
            return;
        }
        //1.首先判断商品是否存在购物车表中
        Cart record=new Cart();
        record.setItemId(itemId);
        record.setUserId(userId);
        Cart cart=cartMapper.selectOne(record);

        if(cart==null){
            //创建一个购物记录
            cart=new Cart();
            cart.setItemId(itemId);
            cart.setUserId(userId);
            cart.setNum(1);
            cart.setUpdated(new Date());
            cart.setCreated(cart.getUpdated());
            //根据商品id查询商品信息
            cart.setItemImage(item.getImage().split(",")[0]);
            cart.setItemPrice(item.getPrice());
            cart.setItemTitle(item.getTitle());
            //将购物车保存到数据库
            this.cartMapper.insert(cart);
        }else{
         //该商品已在购物车中
            cart.setNum(cart.getNum()+1);
            cart.setUpdated(new Date());
            this.cartMapper.updateByPrimaryKeySelective(cart);
        }


    }

    @Override
    public List<Cart> queryCartList(Long userId) {
        Example example=new Example(Cart.class);
        //设置排序条件
        example.setOrderByClause("created DESC");
        example.createCriteria().andEqualTo("userId",userId);
        List<Cart> carts = cartMapper.selectByExample(example);
        return carts;
    }

    @Override
    public void updateCartNum(Long cartId, Integer num) {
        Cart cart = this.cartMapper.selectByPrimaryKey(cartId);
        if(cart!=null){
            cart.setNum(num);
            this.cartMapper.updateByPrimaryKeySelective(cart);
        }
    }

    @Override
    public void deleteCartItem(Long cartId) {
        this.cartMapper.deleteByPrimaryKey(cartId);
    }

    @Override
    public void clearCart(Long userId) {
        //设置条件
        Example example=new Example(Cart.class);
        example.createCriteria().andEqualTo("userId",userId);
        this.cartMapper.deleteByExample(example);
    }


}
